package com.rzjm.exercise.sys.core.file.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.config.ProjectUrlConfig;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.sys.core.file.domain.FileDO;
import com.rzjm.exercise.sys.core.file.service.FileService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 文件上传
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2017-09-19 16:02:20
 */
@Controller
@RequestMapping("/common/sysFile")
public class FileController extends BaseController {

	@Resource
	private FileService sysFileService;

	@Resource
	private ProjectUrlConfig projectUrlConfig;

	@GetMapping()
	@RequiresPermissions("common:sysFile:sysFile")
	String sysFile(Model model) {
		new HashMap<>(16);
		return "common/file/file";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("common:sysFile:sysFile")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<FileDO> sysFileList = sysFileService.list(query);
		long total = sysFileService.selectCountByMap(query);
		PageUtils pageUtils = new PageUtils(sysFileList, total);
		return pageUtils;
	}

	@GetMapping("/add")
	String add() {
		return "common/sysFile/add";
	}

	@GetMapping("/edit")
	String edit(Long id, Model model) {
		FileDO sysFile = sysFileService.getById(id);
		model.addAttribute("sysFile", sysFile);
		return "common/sysFile/edit";
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("common:info")
	public R info(@PathVariable("id") Long id) {
		FileDO sysFile = sysFileService.getById(id);
		return R.ok().put("sysFile", sysFile);
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("common:save")
	public R save(FileDO sysFile) {
		if (sysFileService.save(sysFile)) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("common:update")
	public R update(@RequestBody FileDO sysFile) {
		sysFileService.updateById(sysFile);
		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	// @RequiresPermissions("common:remove")
	public R remove(Long id, HttpServletRequest request) {
		if ("test".equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		String fileName = sysFileService.getById(id).getUrl();
		if (sysFileService.removeById(id)) {
			boolean b = OssUtil.deleteObjByKey(fileName);
			if (!b) {
				return R.error("数据库记录删除成功，文件删除失败");
			}
			return R.ok();
		} else {
			return R.error();
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("common:remove")
	public R remove(@RequestParam("ids[]") Long[] ids) {
		if ("test".equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		List<Long> list = Arrays.asList(ids);
		sysFileService.removeByIds(list);
		return R.ok();
	}

	@ResponseBody
	@PostMapping("/uploadOss")
	R uploadOss(@RequestParam("file") MultipartFile mfImgUrl, Integer upload_type, Integer id, String associatedId, String imgType,Integer isSingle) {
		String img_key = "";
		String fileName = mfImgUrl.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		if (!mfImgUrl.isEmpty()) {
			String prefix = mfImgUrl.getOriginalFilename().substring(mfImgUrl.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
			if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "gif".equals(prefix)) {
				try {
					InputStream inputStream = mfImgUrl.getInputStream();
					if (inputStream != null) {
						String img_url = OssUtil.getUploadPrefix(upload_type) + id + "/" + fileName;
						OssUtil.upload(inputStream, img_url);
						img_key = OssUtil.getUploadPrefix(upload_type) + id + "/" + fileName;
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		if(isSingle == 1){
			QueryWrapper qw = new QueryWrapper();
			qw.eq("img_id",id);
			qw.eq("img_type",imgType);
			FileDO fileDO = sysFileService.getOne(qw);
			if(fileDO!=null){
				fileDO.setUrl(img_key);
				if(sysFileService.updateById(fileDO)){
					return R.ok().put("fileName", fileDO.getUrl()).put("fileId", fileDO.getId());
				}
			}
		}
		FileDO sysFile = new FileDO(FileType.fileType(fileName), img_key, new Date(), associatedId,id,imgType);
		if (sysFileService.save(sysFile)) {
			return R.ok().put("fileName", projectUrlConfig.getImgurl() + sysFile.getUrl()).put("filePath", sysFile.getUrl()).put("fileId", sysFile.getId());
		}
		return R.error();
	}

	@ResponseBody
	@PostMapping("/upload")
	R upload(@RequestParam("file") MultipartFile mfImgUrl, Integer upload_type, Integer id, String associatedId, String imgType,Integer isSingle) {
		String img_key = "";
		String fileName = mfImgUrl.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		String filePath = "";
		if(id!=null && id > 0){
			filePath = OssUtil.getUploadPrefix(upload_type) + id ;
		}else{
			filePath = OssUtil.getUploadPrefix(upload_type) ;
		}
		img_key = filePath + "/" + fileName;
		try {
			File file = new File(projectUrlConfig.getUploadPath() + filePath);
			if(!file.exists()){
				file.mkdirs();
			}
			FileUtil.uploadFile(mfImgUrl.getBytes(), projectUrlConfig.getUploadPath()+ filePath+"/", fileName);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}

		if(isSingle == 1){
			QueryWrapper qw = new QueryWrapper();
			qw.eq("img_id",id);
			qw.eq("img_type",imgType);
			FileDO fileDO = sysFileService.getOne(qw);
			if(fileDO!=null){
				fileDO.setUrl(img_key);
				if(sysFileService.updateById(fileDO)){
					return R.ok().put("fileName", fileDO.getUrl()).put("fileId", fileDO.getId());
				}
			}
		}
		FileDO sysFile = new FileDO(FileType.fileType(fileName), img_key, new Date(), associatedId,id,imgType);
		if (sysFileService.save(sysFile)) {
			return R.ok().put("fileName", projectUrlConfig.getImgurl() + sysFile.getUrl()).put("filePath", sysFile.getUrl()).put("fileId", sysFile.getId());
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping("/del")
	@ResponseBody
	public R delete(@RequestParam("img_url") String img_url) {
		if ("test".equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		String fileUrl  = img_url.replaceAll(projectUrlConfig.getImgurl(),"");
		FileDO fileDO = sysFileService.selectByUniqueColumn("url",fileUrl);
		if(fileDO!=null){
			String url = fileUrl.substring(1,fileUrl.length());
			boolean bl = OssUtil.deleteObjByKey(url);
			if(bl){
				boolean ret = sysFileService.removeById(fileDO.getId());
				if(ret){
					return R.ok();
				}else{
					return R.error("删除失败");
				}
			}else{
				return R.error("删除失败");
			}
		}else{
			return R.error("删除失败");
		}
	}

}
